package org.ws.task.common;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

public final class IndexNumberUtils {

    private IndexNumberUtils(){}

    private static final AtomicReference<Map<String, AtomicInteger>> indexNumberMap = new AtomicReference<>(Maps.newConcurrentMap());

    private static final AtomicLong TaskItemIdIndex = new AtomicLong(0);

    public static int getRequestMessageId(){
        return incrementAndGet("RequestMessageId");
    }

    public static long getTaskItemId(){
        return TaskItemIdIndex.incrementAndGet();
    }

    public static int getBootstrapEventIndex(){
        return incrementAndGet("BootstrapEventIndex");
    }

    public static int incrementAndGet(String name){
        if(!indexNumberMap.get().containsKey(name)){
            indexNumberMap.get().put(name,new AtomicInteger(0));
        }
        return indexNumberMap.get().get(name).incrementAndGet();
    }

    public static int incrementAndGet(String name,int i){
        if(!indexNumberMap.get().containsKey(name)){
            indexNumberMap.get().put(name,new AtomicInteger(0));
        }
        return indexNumberMap.get().get(name).addAndGet(i);
    }

    public static int get(String name){
        if(!indexNumberMap.get().containsKey(name)){
            indexNumberMap.get().put(name,new AtomicInteger(0));
        }
        return indexNumberMap.get().get(name).get();
    }

}
